package org.xiaov.framework.web.filter;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.AbstractRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 描述：
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/12/25 20:46
 */
public class FrameRequestLoggingFilter extends AbstractRequestLoggingFilter {
    @Override
    protected void beforeRequest(HttpServletRequest request, String s) {
        MDC.put("url", request.getRequestURI());

        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        MDC.put("ip", ipAddress);

        //从redis等session存储里面获取userId并填充至MDC
        MDC.put("userId", "get userId from redis");

        String traceId = request.getHeader("X-B3-TraceId");
        MDC.put("X-B3-TraceId", traceId);
        String spanId = request.getHeader("X-B3-SpanId");
        MDC.put("X-B3-SpanId", spanId);
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String s) {
        MDC.remove("url");
        MDC.remove("ip");
        MDC.remove("userId");
        MDC.remove("traceId");
        MDC.remove("spanId");
    }
}
